package com.yiduo.outpost.core.database.config;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.PostgreDialect;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.yiduo.outpost.core.database.handler.AutiablePropertyHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @Author yanwen
 * @create 2023/7/25 14:03
 */
@Configuration
@ConditionalOnClass(MybatisSqlSessionFactoryBean.class)
@MapperScan("com.yiduo.outpost.**.mapper.**")
public class MybatisPlusAutoConfiguration {
    /**
     * 单页分页条数限制(默认无限制,参见 插件#handlerLimit 方法)
     */
    private static final Long MAX_LIMIT = 1000L;
    /**
     * 分页插件
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(PaginationInnerInterceptor.class)
    public PaginationInnerInterceptor paginationInterceptor() {
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        paginationInterceptor.setDialect(new PostgreDialect());
        paginationInterceptor.setMaxLimit(MAX_LIMIT);
        return paginationInterceptor;
    }

    /**
     * 时间解析
     */
    @Bean
    @ConditionalOnMissingBean(AutiablePropertyHandler.class)
    public AutiablePropertyHandler autoFillDateHandler() {
        return new AutiablePropertyHandler();
    }

    /**
     * SQL 默认注入器
     * 添加批量插入
     * @return
     */
    @Bean
    public DefaultSqlInjector myLogicSqlInjector() {
        return new DefaultSqlInjector() {
            @Override
            public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
                List<AbstractMethod> methodList = super.getMethodList(mapperClass,tableInfo);
                methodList.add(new InsertBatchSomeColumn());
                return methodList;
            }
        };
    }

    /**
     * mybatis-plus 乐观锁拦截器
     */
    @Bean
    public OptimisticLockerInnerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInnerInterceptor();
    }
}
